<?php
class db
{
   public $conn = null;
   public static $sql = null;
   public static $instance= null;
   private function __construct(){
     @$this->conn = new mysqli('localhost','root','123456','g7_fuel');
     if($this->conn->connect_errno){
        exit('can not link database');
     }
   }

  //单例模式
   public static function getInstance(){
     if(is_null(self::$instance)){
         self::$instance = new db;
     }
     return self::$instance;
   }
  //查询数据库
  public function select($tableName,$condition=array(),$fields=array()){
     if(empty($tableName)) return;
     $where = '';
	  $start_city = '';
	  $end_city = '';
     if(!empty($condition)){
       foreach($condition as $key=>$v){
		   if($key == "start_city"){
			  $start_city =$v;
		   }else if($key == "end_city"){
			  $end_city = $v;
		   }
		   else{
				$where.=$key."='".$v."' and ";
		   }
       }
	   if ($start_city != '' && $end_city != ''){
		   $where.= " ((start_city = '". $start_city ."' and end_city = '" . $end_city ."') or (start_city = '". $end_city ."' and end_city = '" . $start_city ."')) and ";
	   }
	   
       $where = 'where '.$where.'1=1';
     }
     //查询变量
     $selectStr = '';
     if(!empty($fields)){
       foreach($fields as $v){
         $selectStr.=$v.',';
       }
       $selectStr = rtrim($selectStr,',');
     }else{
       $selectStr = '*';
     }
     //整理sql
     self::$sql = "select {$selectStr} from {$tableName} {$where}";
     if($result=$this->conn->query(self::$sql)){
         $res = $result->fetch_assoc();
         $result->free();
         return $res;
     }
  }

  public function select2($tableName,$where="",$fields=""){
    if(!$tableName || !$fields)
      return null;
    self::$sql = "select {$fields} from {$tableName} where 1=1 AND {$where}";
    $result=$this->conn->query(self::$sql);
    $res = mysqli_fetch_all($result,MYSQLI_ASSOC);
    $result->free();
    return $res;
  }

  public function insertQueryInfo($tableName,$fields,$values){
    if(!$tableName || !$fields || !$values)
      return null;
    self::$sql = "insert into {$tableName} ({$fields}) values({$values})";
    $result=$this->conn->query(self::$sql);
    $res = mysqli_fetch_all($result,MYSQLI_ASSOC);
    return $res;
  }

  //关闭数据库连接
  public function close(){
    $this->conn->close();
  }
}
